import { formateTime } from "../../../utils/tim/common"
import tim from "../../../utils/tim/tim"

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    conversation: {
      type: Object,
      value: {},
      observer(newVal) {
        if (!newVal.conversationID) return
        this.setData({
          conversation: newVal,
        }, () => {
          this.getMessageList(newVal)
        })
      },
    },
    update: {
      type: Number,
      value: 0,
      observer() {
        console.log('会话状态更新');
        this.$onMessageReadByPeer()
      },
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    avatar: '',
    userID: '',
    conversation: {}, // 当前会话
    messageList: [],
    // 自己的 ID 用于区分历史消息中，哪部分是自己发出的
    scrollView: '',
    triggered: true,
    nextReqMessageID: '', // 下一条消息标志
    isCompleted: false, // 当前会话消息是否已经请求完毕
    playingList: [],
  },

  lifetimes: {
    ready() {
      wx.$TUIKit.getMyProfile().then((res) => {
        this.data.avatar = res.data.avatar
        this.data.userID = res.data.userID
      })
      wx.$TUIKit.on(wx.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived, this)
      wx.$TUIKit.on(wx.$TUIKitEvent.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this)
    },
    detached() {
      // 一定要解除相关的事件绑定
      wx.$TUIKit.off(wx.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived)
    },
  },

  methods: {
    refresh() {
      if (this.data.isCompleted) {
        this.setData({
          isCompleted: true,
          triggered: false,
        })
        return
      }
      this.getMessageList(this.data.conversation)
      setTimeout(() => {
        this.setData({
          triggered: false,
        })
      }, 2000)
    },

    getMessageList(conversation) {
      if (!this.data.isCompleted) {
        wx.$TUIKit.getMessageList({
          conversationID: conversation.conversationID,
          nextReqMessageID: this.data.nextReqMessageID,
          count: 15,
        }).then((res) => {
          const { messageList } = res.data // 消息列表。
          this.data.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
          this.data.isCompleted = res.data.isCompleted // 表示是否已经拉完所有消息。
          this.data.messageList = [...messageList, ...this.data.messageList]
          this.$handleMessageRender(this.data.messageList, messageList)
        })
      }
    },
    // 格式化聊天时间
    getTimes(){
      let startTime= this.data.messageList.length>0? this.data.messageList[0].time : ''
      let messageList= this.data.messageList
      messageList.forEach((item,index)=>{
        let time= new Date(item.time*1000)
        let nowTime= new Date()
        if(startTime!= item.time){
          item.timeStr= ''
         // 展示5分钟内时间段
         if(this.data.messageList[index+1] && this.data.messageList[index+1].time > (startTime+5*60)){
          startTime= this.data.messageList[index+1].time
         }
         return
        }else{
          if(this.data.messageList[index+1] && this.data.messageList[index+1].time > (startTime+5*60)){
            startTime= this.data.messageList[index+1].time
          }
        }
        // 不同年展示 年-月-日 时:分
        if(time.getFullYear() !== nowTime.getFullYear()){
          item.timeStr= time.toLocaleString('chinese',{hour12:false}).replace(/:\d{1,2}$/,' ').replace(/\//g,'-')
        }else if(time.getFullYear() === nowTime.getFullYear() && time.getMonth()+1 === nowTime.getMonth()+1 && time.getDate()===nowTime.getDate()){// 同一天 时:分
           item.timeStr= time.getHours() + ":" + (time.getMinutes()<10? '0' + time.getMinutes() : time.getMinutes())
        }else {//  同月 不同月 不同天 展示 月-日 时:分
          item.timeStr=((time.getMonth()+1)+'-'+time.getDate() + ' ' +time.getHours() + ":" + (time.getMinutes()<10? '0' + time.getMinutes() : time.getMinutes())).replace(/\//g,'-')
        }
      })
      this.setData({
        messageList
      })
    },
    // 重新发送消息
    resendMessage(e) {
      const message = this.data.messageList[e.currentTarget.dataset?.index]
      message.fail = false
      message.loading = true
      wx.$TUIKit.sendMessage(message, {
        offlinePushInfo: {
          disablePush: true,
        },
      }).then((res) => {
        // 消息发送成功
        console.log('消息发送成功', res)
        message.loading = false
        this.$onMessageReadByPeer()
      }).catch((err) => {
        message.loading = false
        message.fail = true
        this.$onMessageReadByPeer()
        switch (err.code) {
          case 8004:
          case 30005:
          case 40005:
          case 80001:
            wx.showToast({
              icon: 'none',
              title: '消息中包含不合适的内容',
            })
            break;
          case 2252:
            wx.showToast({
              icon: 'none',
              title: '只允许上传 jpg png jpeg gif bmp格式的图片',
            })
            break;
          case 2253:
            wx.showToast({
              icon: 'none',
              title: '图片上传失败',
            })
            break;
          case 2300:
          case 2301:
            wx.showToast({
              icon: 'none',
              title: '语音上传失败',
            })
            break;
          case 2350:
          case 2351:
            wx.showToast({
              icon: 'none',
              title: '视频上传失败',
            })
            break;
          case 2352:
            wx.showToast({
              icon: 'none',
              title: '只允许上传 mp4 格式的视频',
            })
            break;
          case 2100:
            wx.showToast({
              icon: 'none',
              title: '消息发送失败',
            })
            break;
          case 2800:
            wx.showToast({
              icon: 'none',
              title: '网络错误',
            })
            break;
          case 2801:
            wx.showToast({
              icon: 'none',
              title: '请求超时',
            })
            break;
          case 2805:
            wx.showToast({
              icon: 'none',
              title: '未连接到网络',
            })
            break;
          default:
            wx.showToast({
              icon: 'none',
              title: `未知错误: ${err.code}`,
            })
            break;
        }
        // 消息发送失败
        console.log('消息发送失败', err)
      })
    },
    // 自己的消息上屏
    updateMessageList(msg) {
      this.lastIsMsg = msg.type === 'TIMImageElem'
      this.filterCallingMessage(msg)
      this.data.messageList.push(Object.assign(msg, { isSelf: true }))
      this.setData({
        messageList: this.data.messageList,
        scrollView: this.data.messageList[this.data.messageList.length - 1].ID,
      })
      this.getTimes()
    },
    // 消息已读更新
    $onMessageReadByPeer() {
      this.setData({
        messageList: this.data.messageList,
      })
    },
    // 收到的消息
    $onMessageReceived(value) {
      const conversationID = this.data.conversation.conversationID
      tim.setRead(conversationID)
      // 若需修改消息，需将内存的消息复制一份，不能直接更改消息，防止修复内存消息，导致其他消息监听处发生消息错误
      const event = JSON.parse(JSON.stringify(value))
      const list = []
      event.data.forEach((item) => {
        if (item.conversationID === conversationID) {
          this.filterCallingMessage(item)
          list.push(Object.assign(item))
        }
      })
      this.lastIsMsg = list[list.length - 1]?.type === 'TIMImageElem'
      this.data.messageList = this.data.messageList.concat(list)
      this.setData({
        messageList: this.data.messageList,
        scrollView: this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - 1].ID),
      })
      this.getTimes()
    },
    // 历史消息渲染
    $handleMessageRender(messageList, currentMessageList) {
      for (let i = 0; i < messageList.length; i++) {
        if (messageList[i].flow === 'out') {
          messageList[i].isSelf = true
        }
        // 解析音视频通话消息
        this.filterCallingMessage(messageList[i])
      }
      if (messageList.length > 0) {
        this.setData({
          messageList,
        }, () => {
          if (!this.firstMsgLoaded) {
            this.firstMsgLoaded = true
            this.setData({
              scrollView: this.filterSystemMessageID(this.data.messageList[this.data.messageList.length - 1].ID),
            })
          }
        })
      }
     // 格式化聊天时间
      this.getTimes()
    },

    // 兼容 scrollView
    filterSystemMessageID(messageID) {
      const index = messageID.indexOf('@TIM#')
      if (index > -1) {
        return messageID.replace('@TIM#', '')
      }
      return messageID
    },
    // 解析音视频通话消息
    extractCallingInfoFromMessage(message) {
      if (!message || message.type !== 'TIMCustomElem') {
        return ''
      }
      const signalingData = JSON.parse(message.payload.data)
      if (signalingData.businessID !== 1) {
        return ''
      }
      switch (signalingData.actionType) {
        case 1: {
          const objectData = JSON.parse(signalingData.data)
          if (objectData.call_end > 0 && !signalingData.groupID) {
            return `通话时长：${formateTime(objectData.call_end)}`
          }
          if (objectData.call_end === 0 || !objectData.room_id) {
            return '结束群聊'
          }
          return '发起通话'
        }
        case 2:
          return '取消通话'
        case 3:
          return '已接听'
        case 4:
          return '拒绝通话'
        case 5:
          return '无应答'
        default:
          return ''
      }
    },
    // 音视频通话消息解析
    filterCallingMessage(item) {
      if (item.type === 'TIMCustomElem') {
        let payloadData = {}
        try {
          payloadData = JSON.parse(item.payload.data)
        } catch (e) {
          payloadData = {}
        }
        if (payloadData.businessID === 1) {
          if (item.conversationType === 'GROUP') {
            if (payloadData.actionType === 5) {
              item.nick = payloadData.inviteeList ? payloadData.inviteeList.join(',') : item.from
            }
            const _text = this.extractCallingInfoFromMessage(item)
            const groupText = `${_text}`
            item.type = 'TIMGroupTipElem'
            const customData = {
              operationType: 256,
              text: groupText,
              userIDList: [],
            }
            item.payload = customData// JSON.stringify(customData)
          }
          if (item.conversationType === 'C2C') {
            const c2cText = this.extractCallingInfoFromMessage(item)
            item.type = 'TIMTextElem'
            const customData = {
              text: c2cText,
            }
            item.payload = customData
          }
        }
      }
    },
    // 语音是否有在播放中
    playing(e) {
      const { playingList } = this.data
      const { index, play } = e.detail
      playingList[index] = play

      this.setData({
        playingList,
        ...(play ? {playIndex: index} : {})
      })
    },
    // 图片是否加载完毕
    imageLoad() {
      if (this.firstLoaded) {
        if (this.lastIsMsg) {
          this.lastIsMsg = false
          this.setData({
            scrollView: 't-message-last',
          })
        }
        return
      }
      if (!this.imageLoaded) {
        this.imageLoaded = 0
      }
      this.imageLoaded++
      if (this.imageLoaded === this.data.messageList.filter(f => f.type === 'TIMImageElem').length) {
        this.setData({
          scrollView: 't-message-last',
        })
        this.firstLoaded = true
        this.imageLoaded = 0
      } 
    },
    //菜单展开
    handleShow(){
      this.setData({
        scrollView: 't-message-last',
      })
    }
  },
})
